package com.zf.bm.common.utils;


import org.apache.commons.lang3.Validate;
import org.springframework.context.ApplicationContext;

public class SpringContextHolder {
    private SpringContextHolder(){}

    private static ApplicationContext applicationContext = null;

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String beanName){
        assertContextInjected();
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 从静态变量applicationContext中取得bean,自动转型位所赋值对象的类型
     */
    public static <T> T getBean(Class<T> required){
        assertContextInjected();
        return applicationContext.getBean(required);
    }

    public static void setApplicationContext(ApplicationContext applicationContext){
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 检查applicationContext不为空
     */
    private static void assertContextInjected() {
        Validate.validState(applicationContext != null,"applicationContext属性未注入，请在applicationContext.xml中定义SprinngContextHolder.");
    }
}
